#include "frmdice.h"
#include "ui_frmdice.h"

FrmDice::FrmDice(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FrmDice)
{
    ui->setupUi(this);

    QPalette palette;
    palette.setColor(QPalette::Background,Qt::white);
    this->setPalette(palette);
    this->setAutoFillBackground(true);

    ui->labDice->setPalette(palette);
    ui->labDice->setAutoFillBackground(true);
    ui->labDice->setScaledContents(true);

    connect(&threadA,SIGNAL(started()),this,SLOT(onthreadA_started()));
    connect(&threadA,SIGNAL(finished()),this,SLOT(onthreadA_finished()));
    connect(&threadA,SIGNAL(newValue(int,int)),this,SLOT(onthreadA_newValue(int,int)));

    ui->btnStartThread->setEnabled(true);
    ui->btnStopThread->setEnabled(false);
    ui->btnStart->setEnabled(false);
    ui->btnPause->setEnabled(false);
}

FrmDice::~FrmDice()
{
    delete ui;
}

void FrmDice::onthreadA_started()
{
    ui->labA->setText("线程状态：开始运行");
}
void FrmDice::onthreadA_finished()
{
    ui->labA->setText("线程状态：停止运行");
}
void FrmDice::onthreadA_newValue(int seq,int diceValue)
{
    QString str=QString::asprintf("第%d次掷骰子，点数为%d",seq,diceValue);
    ui->plainTextEdit->appendPlainText(str);
    QPixmap pic;
    QString fileName=QString(":images/dice/dice%1.png").arg(diceValue);
    pic.load(fileName);
    ui->labDice->setPixmap(pic);
}

void FrmDice::on_btnStartThread_clicked()
{
    threadA.start();
    ui->btnStartThread->setEnabled(false);
    ui->btnStopThread->setEnabled(true);
    ui->btnStart->setEnabled(true);
    ui->btnPause->setEnabled(true);
}
void FrmDice::on_btnStopThread_clicked()
{
    threadA.stop();
    ui->btnStartThread->setEnabled(true);
    ui->btnStopThread->setEnabled(false);
    ui->btnStart->setEnabled(false);
    ui->btnPause->setEnabled(false);
}
void FrmDice::on_btnStart_clicked()
{
    threadA.begin();
    ui->btnStart->setEnabled(false);
    ui->btnPause->setEnabled(true);
}
void FrmDice::on_btnPause_clicked()
{
    threadA.pause();
    ui->btnStart->setEnabled(true);
    ui->btnPause->setEnabled(false);
}
void FrmDice::on_btnClearText_clicked()
{
    ui->plainTextEdit->clear();
}

void FrmDice::closeEvent(QCloseEvent *event)
{
    //窗体关闭事件，必须结束线程
    if(threadA.isRunning())
    {
        threadA.stop();
        threadA.wait();
    }
    event->accept();
}
